package controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

import dao.LoginDAO;

import entity.Visitor;

public class LoginAction extends ActionSupport{
	private String userName;
	private String password;
    private String checkremember;
    private HttpServletRequest request;
    private HttpServletResponse response;
    private HttpSession session;
    
    @Override
    public void validate() {
    	// TODO Auto-generated method stub
    	super.validate();
    	if (userName.equals("") || userName.trim().equals("")) {
    		addActionError("username must not be empty!");
    	}
    	if (password.equals("") || password.trim().equals("")) {
    		addActionError("password must not be empty!");
    	}
    }
    
    @Override
    public String execute() throws Exception {
    	// TODO Auto-generated method stub
    	try{
            Visitor visitor = new Visitor();
            visitor.setUserName(userName);
            visitor.setPassword(EncyptPassword.encryptMD5(password));
            
            visitor = LoginDAO.checkVisistor(visitor);
            
            if(visitor.getId() != 0){
                request = ServletActionContext.getRequest();
                session = request.getSession();
                session.setAttribute("curSession", visitor);  
                
                if(checkremember != null && !checkremember.equals("")){
                    Cookie c_u = new Cookie("c_u", visitor.getUserName());
                    c_u.setMaxAge(300);
                    response = ServletActionContext.getResponse();
                    response.addCookie(c_u);
                }
            	return SUCCESS;
            }else {
                addActionError("Invalid username or password.");
                return ERROR;            	
			}
            
    	}catch(Exception ex){
    		addActionError("Invalid username or password."+ex.getMessage());
            return ERROR;
    	}
    }
    
	public String getUserName() {
		return userName;
	}
	
	public void setUserName(String userName) {
		this.userName = userName;
	}
	
	public String getPassword() {
		return password;
	}
	
	public void setPassword(String password) {
		this.password = password;
	}

	public String getCheckremember() {
		return checkremember;
	}

	public void setCheckremember(String checkremember) {
		this.checkremember = checkremember;
	}	
}
